package cn.ygkj.noticespringbootstarter.config;

import cn.ygkj.noticespringbootstarter.entity.NoticeConfig;
import cn.ygkj.noticespringbootstarter.service.NoticeService;
import lombok.ToString;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Aspect
@Component
public class AopAdvice {

    @Autowired
    private NoticeService noticeService;
     @Autowired
    private NoticeConfig noticeConfig;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.GetMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void pointCut() {

    }


    @AfterThrowing(pointcut="pointCut()",throwing= "ex")
    public void afterThrowing(JoinPoint joinPoint, Throwable ex) throws ClassNotFoundException {

        String name = ex.getClass().getName();
        boolean ignore = noticeConfig.getIgnoreException().stream().anyMatch(f -> f.equals(name));
        //需要过滤此异常不做通知
        if (!ignore)
        {
            //拼接通知的信息详情
            MethodSignature me = (MethodSignature)joinPoint.getSignature();
            noticeService.sendMessageByText(createMsg(name,me.getName()),true);
        }
    }

    private String createMsg(String msg,String interName){
        String projectName = noticeConfig.getProjectName();
        StringBuffer buffer = new StringBuffer();
        buffer.append("项目名称：【").append(projectName).append("】\t\n")
                .append("接口名称：【").append(interName).append("】\t\n")
                .append("错误信息：【").append(msg).append("】\t\n");
        return buffer.toString();
    }


}
